package com.ssy.lingxi.marketing.serviceimpl.base;

import cn.hutool.json.JSONUtil;
import com.ssy.lingxi.marketing.api.model.constant.MkFeignConstants;
import com.ssy.lingxi.marketing.api.model.dto.MarketingQueueDTO;
import com.ssy.lingxi.marketing.service.IBaseMqService;
import com.ssy.lingxi.marketing.utils.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 订单相关定时任务接口实现类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-10-21
 */
@Service
@Slf4j
public class BaseMqServiceImpl implements IBaseMqService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 将延迟消息重新加入队列
     *
     * @param queueDTO 消息实体
     * @return 是否需要（或已经）重新加入队列
     */
    @Override
    public Boolean reScheduleDelayMessage(MarketingQueueDTO queueDTO) {
        if(queueDTO == null || NumberUtil.isNullOrZero(queueDTO.getDelayTime()) || queueDTO.getDelayTime() <= (long) Integer.MAX_VALUE) {
            return false;
        }

        long leftTime = queueDTO.getDelayTime() - (long) Integer.MAX_VALUE;
        queueDTO.setDelayTime(leftTime);
        queueDTO.setTimes(queueDTO.getTimes() + 1);

        Integer delayMillSeconds = leftTime >  Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) leftTime;
        try {
            //延迟时间的单位是毫秒
            rabbitTemplate.convertAndSend(MkFeignConstants.MK_DELAY_EXCHANGE, MkFeignConstants.MK_DELAY_ROUTING_KEY, JSONUtil.toJsonStr(queueDTO), message -> {
                message.getMessageProperties().setDelay(delayMillSeconds);
                return message;
            });
            return true;
        } catch (Exception e) {
            log.error("重新推送至延迟消息队列错误，data: " + JSONUtil.toJsonStr(queueDTO) + ", error:" ,e);
            return false;
        }
    }

}
